package com.bsoft.gol.hcs.specialist.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.hcs.specialist.bean.request.GroupChronicRecordQo;
import com.bsoft.gol.hcs.specialist.bean.response.MedicalRecordResponse;
import com.bsoft.gol.hcs.specialist.bean.response.MedicalTimeListResponse;
import com.bsoft.gol.hcs.specialist.entity.PrescriptionRecordEntity;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 处方（用药）记录dao
 * @author lanyu
 * @date 2021年10月14日 11:08
 */
public abstract class PrescriptionRecordDAO extends HibernateSupportDelegateDAO<PrescriptionRecordEntity> {

    @DAOMethod(sql = "from PrescriptionRecordEntity where businessType=:businessType and visitId=:visitId")
    public abstract List<PrescriptionRecordEntity> queryPrescriptionRecordEntityList(@DAOParam("businessType") String businessType,@DAOParam("visitId") String visitId);

    @DAOMethod(sql = "from PrescriptionRecordEntity where visitId=:visitId and visitOrganization=:visitOrganization")
    public abstract PrescriptionRecordEntity getPrescriptionRecordByVisitId(@DAOParam("visitId") String visitId,@DAOParam("visitOrganization")String visitOrganization);
    /**
     * 查询同步数量
     * @param startTime
     * @param endTime
     * @return
     */
    @DAOMethod(sql = "select count(1) from PrescriptionRecordEntity  where  prescriptionDate>=:startTime and prescriptionDate<=:endTime")
    public abstract Long getPrescriptionByToday(@DAOParam("startTime") Date startTime, @DAOParam("endTime") Date endTime);

    /**
     * 根据日期删除记录
     * @param resultDate
     */
    @DAOMethod(sql = "delete from PrescriptionRecordEntity where prescription_date <:resultDate and deleteFlag!='1'")
    public abstract void deletePrescriptOverdueData(@DAOParam("resultDate") Date resultDate);
    /**
     * 更新删除标识
     */
    @DAOMethod(sql = "update PrescriptionRecordEntity set deleteFlag='1' where  businessId in(:businessIdList) ")
    public abstract void updateDeleteFlag(@DAOParam("businessIdList") List<String> businessIdList);

    /**
     * 查询从his同步用药信息
     * @param qo
     * @return
     */
    public List<MedicalRecordResponse> queryPrescriptionRecordList(GroupChronicRecordQo qo){
        HibernateStatelessResultAction<List<MedicalRecordResponse>> action = new AbstractHibernateStatelessResultAction<List<MedicalRecordResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT DISTINCT " +
                        " drug_detail_id AS medicalId, " +
                        " drug_name AS medicalName " +
                        "FROM  " +
                        " prescription_record " +
                        "WHERE " +
                        " id_card =:idCard ");
                sqlBuilder.append(" and prescription_date >=:beginTime and prescription_date <=:endTime GROUP BY drug_detail_id,drug_name");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("idCard", qo.getIdCard());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<MedicalRecordResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, MedicalRecordResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 获取药品使用时间list
     * @param qo
     * @param drugsNumber
     * @return
     */
    public List<MedicalTimeListResponse> queryAnswerMedicalTimeList(GroupChronicRecordQo qo, String drugsNumber) {
        HibernateStatelessResultAction<List<MedicalTimeListResponse>> action = new AbstractHibernateStatelessResultAction<List<MedicalTimeListResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("select drug_detail_id as medicalId,drug_name as medicalName,drug_use_pathways_name as drugUsePathwaysName,medicine_days as medicineDays,drug_using_rate_name as drugUsingRateName,concat(once_dosage,dosage_unit) as medicineNumber,medicine_number*medicine_days as medicineTotal,prescription_date as medicalTime FROM prescription_record WHERE id_card =:idCard and drug_detail_id =:drugsNumber ");
                sqlBuilder.append(" and prescription_date >=:beginTime and prescription_date <=:endTime order by prescription_date ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("idCard", qo.getIdCard());
                query.setParameter("drugsNumber", drugsNumber);
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<MedicalTimeListResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, MedicalTimeListResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
